<template>
  <div class="container">
    <div class="search-box">
      <el-button
        type="primary"
        size="mini"
        @click="addRoleVisible = true"
      >新增角色</el-button>
      <!-- <icon-picker v-model="icon" style="width: 300px" /> -->
    </div>
    <div class="box">
      <div class="box-left">
        <div class="menu-box-title">菜单列表</div>
        <el-tree
          ref="tree"
          :data="tree"
          node-key="id"
          highlight-current
          :props="defaultProps"
          :expand-on-click-node="false"
        >
          <span
            slot-scope="{ node, data }"
            class="custom-tree-node left-tree-box"
          >
            <div><i :class="data.icon" />{{ node.label }}</div>
            <div v-if="node.level === 1">
              <el-button
                type="text"
                size="mini"
                @click="() => editIcon(node, data)"
              >
                更换图标
              </el-button>
            </div>
          </span>
        </el-tree>
      </div>
      <div class="box-right">
        <el-table :data="data" border style="width: 100%">
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.row.roleId)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.roleId)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="新增角色" :visible.sync="addRoleVisible" width="30%">
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" />
        </el-form-item>
        <el-form-item label="角色菜单" prop="menuList">
          <el-tree
            ref="addRoleTree"
            :data="tree"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑图标" :visible.sync="iconVisible" width="30%">
      <div class="icon-dialog">
        <!-- <i :class="icon"></i> -->
        <el-popover width="600" trigger="click">
          <div
            style="max-height: 400px; overflow-y: scroll; overflow-x: hidden"
          >
            <el-button
              v-for="(item, index) in iconList"
              :key="index"
              plain
              style="margin: 2px"
              @click="iconName = item"
            >
              <i :class="item" style="font-size: 20px" />
            </el-button>
          </div>

          <el-button slot="reference">
            <span v-if="iconName === ''">请选择图标</span>
            <span v-else>
              <i :class="iconName" style="font-size: 20px" />
            </span>
          </el-button>
        </el-popover>
      </div>
      <div slot="footer">
        <el-button @click="iconVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateIcon()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑角色" :visible.sync="editVisible" width="30%">
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" />
        </el-form-item>
        <el-form-item label="角色菜单" prop="editMenuList">
          <el-tree
            ref="editRoleTree"
            :data="tree"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { elementIcons } from '@/icons/icon'
import { getAllMenu, addRole, deleteRole, roleMenu, updateMenuIcon, getMenuByRole, updateRole } from '@/api/roleMenu'
export default {
  data() {
    var validateMenu = (rule, value, callback) => {
      const arr = this.$refs.addRoleTree.getCheckedKeys()
      if (arr.length === 0 || !arr) {
        callback(new Error('请选择角色菜单'))
      } else {
        callback()
      }
    }
    var validateEditMenu = (rule, value, callback) => {
      const arr = this.$refs.editRoleTree.getCheckedKeys()
      if (arr.length === 0 || !arr) {
        callback(new Error('请选择角色菜单'))
      } else {
        callback()
      }
    }
    return {
      data: [
        {
          roleName: '测试'
        }
      ],
      icon: '',
      userChooseIcon: '',
      chooseIcons: '',
      iconName: '',
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      addRoleVisible: false,
      addForm: {
        roleName: '',
        menuList: []
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        menuList: [
          { required: true, validator: validateMenu, trigger: 'change' }
        ],
        editMenuList: [
          { required: true, validator: validateEditMenu, trigger: 'change' }
        ]
      },
      iconVisible: false,
      menuId: '',
      editVisible: false,
      editForm: {
        roleName: '',
        roleId: '',
        menuList: []
      }
    }
  },
  watch: {
    icon: {
      handler: function(newValue) {
        this.iconName = newValue
      }
    },
    iconName: {
      handler: function(value) {
        this.$emit('iconName', value)
      }
    }
  },
  created() {
    this.iconList = elementIcons
    this.getAllMenu()
    this.getAllRoleList()
  },
  methods: {
    // 时间格式转换
    formatDate(time) {
      const timestamp = new Date(time)
      const y = timestamp.getFullYear()
      const m = timestamp.getMonth() + 1
      const d = timestamp.getDate()
      const h = timestamp.getHours()
      const mm = timestamp.getMinutes()
      const s = timestamp.getSeconds()
      return y + '-' + this.repair0(m) + '-' + this.repair0(d) + ' ' + this.repair0(h) + ':' + this.repair0(mm) + ':' + this.repair0(s)
    },
    // 日期格式补0
    repair0(m) {
      return m < 10 ? '0' + m : m
    },
    // 获取角色列表
    getAllRoleList() {
      roleMenu().then((res) => {
        this.data = res.data
      })
    },
    setIcon(icon) {
      this.userChooseIcon = icon// 将i的样式设为选中的样式el-icon-xxx
      this.chooseIcons = ''
    },
    // 获取所有菜单
    getAllMenu() {
      getAllMenu().then((res) => {
        this.tree = res.data
      })
    },
    // 提交新增菜单
    addRoleSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addForm.menuList = this.$refs.addRoleTree.getCheckedKeys()
          addRole(this.addForm).then((res) => {
            this.getAllRoleList()
            this.$message.success('新增成功')
            this.$refs.addRoleTree.setCheckedKeys([])
            this.addRoleVisible = false
            this.$refs['addForm'].resetFields()
          }).catch(() => {
            this.addRoleVisible = false
            this.$refs['addForm'].resetFields()
          })
          return
        }
        return false
      })
    },
    // 点击编辑角色
    handleEdit(id) {
      getMenuByRole({
        roleId: id
      }).then((res) => {
        this.editForm.roleName = res.data.roleName
        this.editForm.roleId = id
        const menuData = res.data.menuVoList
        const combinedMenu = menuData.reduce((result, item) => {
          if (!item.children) {
            // 一级菜单项直接添加到结果数组
            result.push(item)
          } else {
            // 二级菜单项合并到结果数组
            result.push(...item.children)
          }
          return result
        }, [])
        this.$refs.editRoleTree.setCheckedNodes(combinedMenu)
      })
      this.editVisible = true
    },
    // 点击编辑角色确定
    handleEditSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editForm.menuList = this.$refs.editRoleTree.getCheckedKeys()
          updateRole(this.editForm).then((res) => {
            this.getAllRoleList()
            this.$message.success('编辑成功')
            this.editVisible = false
            this.$refs.editRoleTree.setCheckedKeys([])
          })
          return
        }
        this.$message.warning('请填写完整')
        return false
      })
    },
    // 编辑图标
    editIcon(node, item) {
      this.iconVisible = true
      this.menuId = item.id
      this.icon = item.icon
    },
    // 更新图标
    updateIcon() {
      if (this.iconName !== '') {
        updateMenuIcon({
          menuId: this.menuId,
          iconPath: this.iconName
        }).then((res) => {
          this.$message.success('编辑成功')
          this.getAllMenu()
          this.iconName = ''
          this.menuId = ''
          this.icon = ''
          this.iconVisible = false
        })
        return
      }
      this.$message.warning('请选择图标')
    },
    // 点击删除
    handleDelete(id) {
      this.$confirm('确定删除该角色吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole({
            roleId: id
          }).then((res) => {
            this.$message.success('删除成功')
            this.getAllRoleList()
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}
.box {
  display: flex;
  margin-top: 10px;
}
.box-left {
  width: 240px;
  padding-right: 10px;
  /* border-right: 1px solid #eee; */
}
.menu-box-title {
  height: 30px;
  line-height: 30px;
  font-weight: bold;
}
.box-right {
  width: calc(90vw - 240px);
}
.search-box {
  margin-bottom: 10px;
}
.iconList {
  width: 400px;
  height: 300px;
  overflow-y: scroll;
  overflow-x: hidden;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.iconList i {
  display: inline-block;
  width: 60px;
  height: 45px;
  color: #000000;
  font-size: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  line-height: 45px;
  margin: 5px;
}

.iconList i:hover {
  color: #409eff;
  border-color: #409eff;
}

.left-tree-box {
  display: flex;
  width: 200px;
  justify-content: space-between;
  align-items: center;
}
.icon-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}
div /deep/ .el-dialog {
  margin-top: 20px !important;
  border-radius: 8px;
}
</style>
